<template>
	<view class="container" :style="'height:'+ screenHeight +'px !important;'">

		<uni-nav-bar dark :fixed="true" backgroundColor="" status-bar left-icon="left" :leftWidth="100" :border="false">
			<block slot="left">
				<view class="user_info" v-show="user.open_id!=null">
					<view v-show="user.open_id!=null">
						<image :src="user.avatarUrl"></image>
					</view>
					<view class="sign_info" v-show="user.open_id!=null">
						<text>已签到</text>
						<view class="sign_day">
							<text class="sign_day_number">{{ user.incr_num }}</text>
							<text class="sign_number_day">天</text>
						</view>
					</view>
				</view>
				<view class="user_info" v-show="user.open_id==null">
					<view class="sign_in" v-show="user.open_id==null" @click="wxLogin">登 录</view>
				</view>
			</block>

			<view class="input-view" @click="search">
				<uni-icons class="input-uni-icon" type="search" size="18" color="#ffffff" />
				<input confirm-type="search" disabled="true" class="nav-bar-input" type="text" placeholder="搜索关键词"
					placeholder-style=“color:#e5d3bf;” @confirm="confirm" />
			</view>
		</uni-nav-bar>
		<view class="list_cont">
			<view class="grade" @click="chooseGrade">
				<text>{{grade_info.grade_name==null?"年级":grade_info.grade_name}}</text>
				<image style="width: 30rpx;height: 30rpx;" src="/static/image/diandian.png"></image>
			</view>
			<scroll-view class="scroll_view" :style="'height:'+ body_height +'px !important;'" scroll-y="true"
				scroll-with-animation="true">
				<view class="item_content" v-for="item in unit_list" :key="item">
					<view class="item_unit"><text>{{item}}</text></view>
					<block v-for="aritcle in article_list" :key="aritcle.info_id">
						<block v-if="aritcle.unit_name==item">
							<uni-card padding="0" spacing="0" @click="itemclick(aritcle)" margin="0">
								<view class="item_card">
									<view class="item_card_box">
										<view>
											<text class="item_card_title">{{aritcle.title}}</text>
										</view>
										<view>
											<text class="item_card_author">{{aritcle.article_from}}</text>
										</view>
										<view class="item_card_text">
											<text class="uni-body uni-mt-5">{{aritcle.summery}}</text>
										</view>
									</view>
									<view class="item-arrow">
										<image style="width: 17rpx;height: 30rpx;" src="/static/image/jt.png"></image>
									</view>
								</view>
							</uni-card>
							<view style="height: 20rpx;"></view>
						</block>
					</block>
				</view>
				<aui-loading ref="auiLoading" :type="5" :mask="true" :direction="col" :styles="{zIndex: 10001}"
					:theme="1" />
			</scroll-view>

		</view>

		<view v-show="!is_sign && user.open_id!=null && grade_info!=null">
			<view class="popbg" :style="'height:'+ (screenHeight+100) +'px !important;'">
				<view class="pop_box">
					<image mode="aspectFill" src="../../static/image/qdbg.png"></image>
					<view class="pop_title">
						<view class="title_1"> <text>{{today | formatDate}} </text> </view>
						<view class="title_2"> <text>坚持是一种温暖的力量</text> </view>
					</view>
					<view class="sign_day_count"> <text>{{ user.incr_num+1 }}</text> <text class="sign_day">天</text>
					</view>
					<view class="sign_button" @click="setSign"><text>完成打卡</text></view>
				</view>
			</view>
		</view>

	</view>


</template>

<script>
	import api from './chapters.js'
	export default {
		data() {
			return {
				user: {},
				grade_info: {},
				article_list: [],
				//单元列表;
				unit_list: [],
				screenHeight: 0,
				body_height: 0,
				is_sign: true,
				today: new Date().toISOString().slice(0, 10),
			}
		},
		onLoad(options) {
			//自带扫码进来的
			// if (getApp().globalData.bbcode.length > 1) {
			// 	this.grade_info.edition_code = getApp().globalData.bbcode;
			// 	this.grade_info.grade_code = getApp().globalData.njcode;
			// 	this.grade_info.stage_code = getApp().globalData.xdcode;
			// 	this.grade_info.subject_code = getApp().globalData.xkcode;
			// 	this.grade_info.grade_name = getApp().globalData.njname;
			// 	//用完清除缓存的数据;
			// 	getApp().globalData.bbcode = '';
			// 	getApp().globalData.njcode = '';
			// 	getApp().globalData.xdcode = '';
			// 	getApp().globalData.xkcode = '';
			// 	getApp().globalData.njname = '';

			// 	this.getArticleByGrade();
			// } else {
			// 	if (!options.hasOwnProperty("bbcode")) {
			// 		uni.redirectTo({
			// 			url: '/pages/scan/scan'
			// 		})
			// 	}
			// 	//微信扫码直接定位到年级;
			// 	else if (options != null && null != options.bbcode) {
			// 		this.grade_info.edition_code = options.bbcode;
			// 		this.grade_info.grade_code = options.njcode;
			// 		this.grade_info.stage_code = options.xdcode;
			// 		this.grade_info.subject_code = options.xkcode;
			// 		this.grade_info.grade_name = options.njname;
			// 		this.getArticleByGrade();
			// 	}
			// }
			// this.share.path = '/pages/chapters/chapters';
			// uni.showShareMenu({
			// 	withShareTicket: true,
			// 	menus: ["shareAppMessage", "shareTimeline"] //不设置默认发送给朋友
			// })
			// this.screenHeight = uni.getSystemInfoSync().windowHeight;
			// let height = uni.getSystemInfoSync().screenHeight;
			// if (height < 750) {
			// 	this.body_height = this.screenHeight - uni.upx2px(200);
			// } else {
			// 	this.body_height = this.screenHeight - uni.upx2px(240);
			// }
			this.getCacheUserInfo();
		},
		// onReady() {
		// 	  this.$refs.auiLoading.show();
		// },
		onShow() {
			let that = this;
			uni.$on('updateGradeData', function(data) {
				let gradeJson = decodeURIComponent(data);
				that.grade_info = JSON.parse(gradeJson);
				that.getArticleByGrade();
				//写缓存;
				uni.setStorage({
					key: 'cache_grade_info',
					data: that.grade_info,
					success: function() {}
				});
			});
			that.setTabBar();
		},

		methods: {
			search() {
				uni.navigateTo({
					url: '/pages/search/search'
				})
			},
			chooseGrade() {
				// uni.navigateTo({
				// 	url: '/pages/grade/grade?grade=' + encodeURIComponent(JSON.stringify(this.grade_info))
				// })
			},
			itemclick(article) {
				//传的是对像，转成json字符串;
				uni.navigateTo({
					url: '/pages/article/article?article=' + encodeURIComponent(JSON.stringify(article))
				})
				// uni.navigateTo({
				// 	url: '/pages/article/article?url=' + encodeURIComponent(article.url)
				// })
			},

			getCacheGradeInfo() {
				let that = this;
				uni.getStorage({
					key: 'cache_grade_info',
					success(res) {
						that.grade_info = res.data;
						that.getArticleByGrade();
					},
					fail() {
						uni.navigateTo({
							url: '/pages/grade/grade?grade=' + encodeURIComponent(JSON.stringify(that
								.grade_info))
						})
					}
				})
			},

			getCacheUserInfo() {
				let that = this;
				//读用户信息缓存;
				uni.getStorage({
					key: 'cache_user_info',
					success(res) {
						that.user = res.data;
						if (null == that.user || null == that.user.open_id || null == that.user.avatarUrl) {
							that.wxLogin();
						} else {
							//取打卡天数;更新;
							that.getSign();
						}
					},
					fail() {
						that.wxLogin();
					}
				})
			},
			wxLogin() {
				let that = this
				uni.showModal({
					mask: true,
					title: '温馨提示',
					content: '授权微信登录后,才能使用小程序的完整功能！',
					success(res) {
						if (res.confirm) {
							uni.getUserProfile({
								desc: '获取你的昵称、头像',
								success: userRes => {
									uni.login({
										provider: 'weixin',
										success(loginAuth) {
											that.userLogin(loginAuth.code, userRes.iv, userRes
												.encryptedData, userRes.userInfo);
										}
									})
								},
								fail: error => {
									console.log(error);
									uni.showToast({
										icon: "none",
										title: "获取失败，请重试"
									})
								}
							});
						} else if (res.cancel) {}
					}
				});
			},

			setTabBar() {
				let that = this;
				if (that.is_sign) {
					uni.showTabBar()
				} else {
					uni.hideTabBar()
				}
			},

			//发送请求，取openID;
			async userLogin(code, iv, encryptedData, userInfo) {
				let that = this;
				let res = await api.userLogin(code, iv, encryptedData, userInfo);
				let resdata = res.data.data;
				that.is_sign = resdata.is_clock_in;
				that.user = {
					'avatarUrl': userInfo.avatarUrl,
					'nickName': userInfo.nickName,
					'open_id': resdata.open_id,
					'incr_num': resdata.incr_num
				};
				//写缓存;
				uni.setStorage({
					key: 'cache_user_info',
					data: that.user,
					success: function() {}
				});
				that.setTabBar();
			},

			//取签到天数
			async getSign() {
				let that = this;
				let res = await api.getSign(that.user.open_id);
				let resdata = res.data.data;
				that.user.incr_num = resdata.incr_num;
				that.is_sign = resdata.is_clock_in;
				//写缓存;
				uni.setStorage({
					key: 'cache_user_info',
					data: that.user,
					success: function() {}
				});
				that.setTabBar();
			},

			//打卡
			async setSign() {
				let that = this;
				if (that.is_sign) {
					return;
				}
				let res = await api.setSign(this.user.open_id);
				let number = res.data.data;
				that.user.incr_num = number;
				that.is_sign = true;
				//写缓存;
				uni.setStorage({
					key: 'cache_user_info',
					data: that.user,
					success: function() {}
				});
				uni.showTabBar()
			},
			
			async getArticleByGrade() {
				this.$refs.auiLoading.show();
				this.article_list = [];
				this.unit_list = [];
				let res = await api.getArticleByGrade(this.grade_info.edition_code, this.grade_info.grade_code, this
					.grade_info.stage_code, this.grade_info.subject_code);
				this.$refs.auiLoading.hide();
				if (res.data.errcode == "0") {
					this.article_list = res.data.data;
					let i = 0;
					for (let item of this.article_list) {
						if (this.unit_list.indexOf(item.unit_name) == -1) {
							this.unit_list.push(item.unit_name);
						}
						this.article_list[i++].summery = item.summery.replaceAll("\n", "");
					}
				} else {
					uni.showToast({
						title: '数据错误',
						icon: 'none',
						duration: 2000
					});
				}
			},
		},
		filters: {
			formatDate: function(value) {
				let day = value.replace("-", "年");
				day = day.replace("-", "月");
				day = day + "日";
				return day;
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "./chapters.scss";
</style>
